package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.util.Consts;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

//缓存短信
@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {
    @Autowired
    private StringRedisTemplate template;


    @Override
    public void sendVerifyCode(String phone, String code) {
        //把key改个唯一的名字
        //String key= "Verify_code:"+phone;
        String key = RedisKeys.VERIFY_CODE.join(phone);
        //参数：key、value、时间、时间单位
        template.opsForValue().set(key, code, RedisKeys.VERIFY_CODE.getTime(), TimeUnit.SECONDS);


    }

    @Override
    public String setToken(UserInfo user) {
        //创建token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //以token为key，user为value存进redis
        String key = RedisKeys.USER_TOKEN.join(token);
        template.opsForValue().set(key, JSON.toJSONString(user), RedisKeys.USER_TOKEN.getTime(), TimeUnit.SECONDS);
        return token;
    }

    //获取验证码
    @Override
    public String getVerifyCode(String phone) {
        String key = RedisKeys.VERIFY_CODE.join(phone);
        String code = template.opsForValue().get(key);
        return code;
    }

    @Override
    //根据令牌获取user对象
    public UserInfo getUserInfoByToken(String token) {
        //判断token不等于null
        if (!StringUtils.hasLength(token)) {
            return null;
        }
        String key = RedisKeys.USER_TOKEN.join(token);
        //判断redis有没有这个key
        if (template.hasKey(key)) {
            String u = template.opsForValue().get(key);
            //判断用户这个字符串
            if (StringUtils.hasLength(u)) {
                //字符串转成对象
                UserInfo userInfo = JSON.parseObject(u, UserInfo.class);
                //重置30分钟
                template.expire(key, RedisKeys.USER_TOKEN.getTime(), TimeUnit.SECONDS);
                return userInfo;
            }
        }


        return null;
    }
}
